package com.zidian.study.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.activity.AddTaskActivity;
import com.zidian.study.activity.TaskActionDetailActivity;
import com.zidian.study.adapter.TaskActionAdapter;
import com.zidian.study.bean.TaskActionBean;
import com.zidian.study.event.AttendActionEvent;
import com.zidian.study.globa.BaseFragment;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by tangyangkai on treasure_chest16/5/10.
 */
public class TaskFragment extends BaseFragment {

    @Bind(R.id.task_add_iv)
    ImageView taskAddIv;
    @Bind(R.id.no_data_view)
    LinearLayout noDataView;
    @Bind(R.id.swipe_refresh_widget)
    SwipeRefreshLayout mSwipeRefreshWidget;
    @Bind(R.id.list)
    RecyclerView mRecyclerView;

    private boolean isLoading;
    private boolean isRefreshing = false;
    private TaskActionAdapter adapter;
    private Handler handler = new Handler();
    private int row;
    private List<TaskActionBean.DataBean> dataBeanList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.tab_fragment_task;
    }


    public static TaskFragment newInstance() {

        return new TaskFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        adapter = new TaskActionAdapter(getActivity(), dataBeanList);
        init();
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAttendActionEvent(AttendActionEvent event) {
        if (event.isAttendEd()) {
            mSwipeRefreshWidget.setRefreshing(true);
            try {
                dataBeanList.clear();
                row = 1;
                run("1");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void init() {

        mSwipeRefreshWidget.setColorSchemeResources(R.color.green);

        mSwipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                if (mSwipeRefreshWidget != null) {
                    mSwipeRefreshWidget.setRefreshing(true);
                }
                isRefreshing = true;
            }
        });
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    dataBeanList.clear();
                    row = 1;
                    isRefreshing = true;
                    run("1");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = mSwipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        try {
                            row++;
                            run(row + "");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new TaskActionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                Intent intent = new Intent();
                intent.setClass(mActivity, TaskActionDetailActivity.class);
                intent.putExtra("activityId", dataBeanList.get(position).getActivityId());
                intent.putExtra("imageUrl", dataBeanList.get(position).getActivityPictureUrl());
                intent.putExtra("functionAttendance", dataBeanList.get(position).getFunctionAttendance());
                intent.putExtra("functionAttendanceSum", dataBeanList.get(position).getFunctionAttendanceSum());
                mActivity.startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {


            }
        });

    }

    @OnClick(R.id.task_add_iv)
    public void addTask() {
        startActivity(AddTaskActivity.class);
    }

    public void initData() {
        try {
            run("1");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取测试数据
     */
    private void getData() {
        adapter.notifyDataSetChanged();
        if (mSwipeRefreshWidget != null) {
            mSwipeRefreshWidget.setRefreshing(false);
        }
        adapter.notifyItemRemoved(adapter.getItemCount());
    }


    public void run(String startrow) throws IOException {
        String url = Constant.URL_GOAL + "activity/select";

        Map<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("activityTitle", "");
        map.put("studentId", GetUserInfo.getStudentId(mActivity));
        map.put("token", GetUserInfo.getToken(mActivity));


        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("T", e.toString());
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
            }

            @Override
            public void onResponse(String response, int id) {
                if (mSwipeRefreshWidget != null) {
                    mSwipeRefreshWidget.setRefreshing(false);
                }
                isRefreshing = false;
                Log.e("T", response);

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {

                        if (resultCode == 201) {
                            isLoading = true;
                            adapter.setMore(false);
                            noDataView.setVisibility(View.VISIBLE);
                            return;
                        }

                        ToastUtil.showToast(mActivity.getApplication(), "获取活动失败！");
                        return;
                    }

                } catch (JSONException e) {


                }

                Gson gson = new Gson();
                TaskActionBean actionBean = gson.fromJson(response, TaskActionBean.class);

                if (actionBean.isSuccess()) {

                    if (actionBean.getData().size() < 10) {
                        isLoading = true;
                        adapter.setMore(false);
                        mSwipeRefreshWidget.setRefreshing(false);
                    } else {
                        isLoading = false;
                        adapter.setMore(true);
                        if (mSwipeRefreshWidget != null) {
                            mSwipeRefreshWidget.setRefreshing(false);
                        }
                    }
                    dataBeanList.addAll(actionBean.getData());
                    if (noDataView != null) {
                        noDataView.setVisibility(View.GONE);
                    }
                    getData();
                }

            }
        });

    }
}
